<template>
    <div class="account">

        <!-- 贴顶导航 -->
        <UserFixedHead title="My account" />

        <!-- 初始化 -->
        <UxIniting v-if="!inited" />

        <template v-else>

            <h2>My account</h2>
            <h3>My profile</h3>
            <el-form class="account-form" :model="form" :rules="rules" ref="refForm">
                <el-form-item label="Full name" prop="name">
                    <el-input v-model="form.name" placeholder="Please enter full name"></el-input>
                </el-form-item>
                <el-form-item label="Company name (optional)" prop="company">
                    <el-input v-model="form.company" placeholder="Please enter company name "></el-input>
                </el-form-item>

                <el-form-item label="Email" prop="contact_email">
                    <el-input v-model="form.contact_email" onkeyup="this.value=this.value.replace(/(\s*)/g,'')" placeholder="Please enter contact email"></el-input>
                </el-form-item>

                <el-form-item label="Phone number (optional)" prop="phone">
                    <el-input v-model="form.phone" placeholder="Please enter your phone number"></el-input>
                </el-form-item>

                <div class="account-submit" :class="{active:this.saveShow}">
                    <button type="primary" @click="onSubmit()">Save</button>
                </div>

            </el-form>

            <h3>Email preference center</h3>
            <div class="account-email">
                <ul>
                    <li :class="{active: emailData.info}">
                        <img src="@/assets/images/setting/setting-account-email1.png" alt="">
                        <p>
                            <strong>Important announcements</strong>
                            <span>Essential information about the website</span>
                        </p>
                        <em @click="putEmailSubscribe('info')"></em>
                        <UxLoadingInline :loading="emailLoading.info" />
                    </li>
                    <li :class="{active: emailData.order}">
                        <img src="@/assets/images/setting/setting-account-email2.png" alt="">
                        <p>
                            <strong>Order status notifications</strong>
                            <span>Order & shipping updates</span>
                        </p>
                        <em @click="putEmailSubscribe('order')"></em>
                        <UxLoadingInline :loading="emailLoading.order" />
                    </li>
                    <li :class="{active: emailData.update}">
                        <img src="@/assets/images/setting/setting-account-email3.png" alt="">
                        <p>
                            <strong>Products updates & new features</strong>
                            <span>New clothing styles & website functions</span>
                        </p>
                        <em @click="putEmailSubscribe('update')"></em>
                        <UxLoadingInline :loading="emailLoading.update" />
                    </li>
                    <li :class="{active: emailData.marketing}">
                        <img src="@/assets/images/setting/setting-account-email4.png" alt="">
                        <p>
                            <strong>Marketing tips & user guides</strong>
                            <span>Seller success stories & practical tips</span>
                        </p>
                        <em @click="putEmailSubscribe('marketing')"></em>
                        <UxLoadingInline :loading="emailLoading.marketing" />
                    </li>
                </ul>
            </div>

            <h3>Login information</h3>
            <div class="account-loginInfo">

                <!-- google登录 -->
                <p v-if="form.oauth_type == 1">
                    <img src="@/assets/images/setting/setting-account-info1.png">
                    <span>Login email：</span>
                    <img src="@/assets/images/google.svg">
                    <strong v-text="form.email"></strong>
                </p>

                <!-- 账号登录 -->
                <template v-if="form.oauth_type == 0">
                    <p>
                        <img src="@/assets/images/setting/setting-account-info1.png">
                        <span>Registered email：</span>
                        <strong v-text="form.email"></strong>
                    </p>
                    <p>
                        <img src="@/assets/images/setting/setting-account-info2.png">
                        <span>Password：</span>
                        <em>●●●●●●●●●●</em>
                    </p>
                    <button @click="changePsw($event)">Change</button>
                </template>

            </div>

            <UxLoading2 :loading="loading" />

        </template>

        <UserAccountPsw v-model="email" />

    </div>
</template>
<script>
import { mapGetters, mapState } from "vuex";
export default {
    name: "UserSettingsAccount",
    layout: "layout-user",
    data () {

        return {
            inited: false,
            notify: false,
            images: true,
            email: null,
            userInfo: null,
            rules: {
                name: [{
                    validator: (rule, value, callback) => {
                        if (value == "") {
                            callback(new Error("Full name cannot be empty"));
                        } else {
                            callback();
                        }
                    }, trigger: "blur"
                }],
                contact_email: [
                    {
                        validator: (rule, value, callback) => {
                            if (value == "") {
                                callback(new Error("Contact email cannot be empty"));
                            } else {
                                let RegExp =
                                    /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
                                if (RegExp.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error("Mailbox format error"));
                                }
                            }
                        }, trigger: "blur"
                    },
                ],
            },
            cache: '',
            form: {
                company: '',
                name: '',
                contact_email: '',
                phone: '',
            },
            loading: true,
            emailData: {
                info: false,
                order: false,
                update: false,
                marketing: false,
            },
            emailLoading: {
                info: false,
                order: false,
                update: false,
                marketing: false,
            },
            option: null,
        };
    },
    computed: {
        saveShow () {
            return JSON.stringify(this.form) != this.cache;
        },
        ...mapGetters("user", {
            getPopupAccess: 'getPopupAccess',
            storeUserInfo: "getUserInfo",
        }),
    },
    methods: {

        async getUserInfo () {
            this.loading = true;
            await this.$store.dispatch("user/updateUserInfo", { force: true, source: 'account' });

            this.loading = false;
            this.userInfo = JSON.parse(JSON.stringify(this.storeUserInfo));
            this.form = Object.assign(this.form, this.userInfo);
            this.cache = JSON.stringify(this.form);
            this.getEmailData(this.userInfo);
        },

        getEmailData (num) {
            num = num.email_subscribe || 0;
            let query = this.$route.query;
            let option = query.option || null;
            let keyObj = {
                info: 1,
                order: 2,
                update: 4,
                marketing: 8,
            }
            Object.keys(keyObj).map(key => {
                if (num & keyObj[key]) {
                    this.$set(this.emailData, key, true)
                } else {
                    this.$set(this.emailData, key, false)
                }
            })

            if (option) {
                const value = this.emailData[option];
                if (value) {
                    this.emailData[option] = false;
                    this.putEmailSubscribe(option);
                } else if (value !== undefined) {
                    this.$uxMessage.success(`Unsubscribed ${option} success`)
                };
                let newQuery = JSON.parse(JSON.stringify(this.$route.query));
                delete newQuery.option;
                this.$router.replace({ query: newQuery })
            }

        },
        changePsw (event) {
            this.email = {};
            event.stopPropagation();
            event.preventDefault();
        },
        onSubmit () {
            this.$refs.refForm.validate((valid) => {
                if (valid) {
                    this.doPut();
                } else {
                    return false;
                }
            });
        },
        async doPut () {
            let arr = ["company", "name", "phone", "contact_email"];
            let formData = {};
            arr.map((key) => {
                formData[key] = this.form[key];
            });
            this.loading = true;
            let res = await this.$http("User.putUserInfo", formData);
            if (res.code == 0) {
                await this.getUserInfo();
            } else {
                this.$uxMessage.warning(res.msg);
                this.loading = false;
            }

        },
        async putEmailSubscribe (option) {
            this.emailLoading[option] = true
            let res = await this.$http('putEmailSubscribe/' + option)
            if (res.code == 0) {
                this.emailLoading[option] = false;
                let data = JSON.parse(JSON.stringify(this.userInfo));
                data.email_subscribe = res.data;
                this.emailData[option] = !this.emailData[option]
                this.$store.dispatch("user/setUserInfo", data);
                if (this.emailData[option]) {
                    this.$uxMessage.success(`Subscribed ${option} success`)
                } else {
                    this.$uxMessage.success(`Unsubscribed ${option} success`)
                }

            } else {
                if (this.emailData[option]) {
                    this.$uxMessage.error(`Failed to subscribed ${option}`)
                } else {
                    this.$uxMessage.error(`Failed to unsubscribed ${option}`)
                }
                this.emailLoading[option] = false;
                this.emailData[option] = !this.emailData[option];
            }
        }
    },
    created () {
        if (process.client) {
            this.getUserInfo().then(() => {
                this.inited = true
            });
        }
    },
    mounted () {
    },
};
</script>
<style lang="scss" scoped>
.account {
    display: flex;
    flex-direction: column;
    position: relative;
    & > .loading {
        position: fixed;
        left: 228px;
        top: 0;
        bottom: 0;
        right: 0;
    }

    & > .initing {
        flex: 1;
        width: 100%;
    }

    & > h2 {
        display: flex;
        align-items: center;
        font-size: 36px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 40px;
    }

    & > h3 {
        margin-top: 40px;
        font-size: 18px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 18px;
        margin-bottom: 18px;
    }
}

.account-form {
    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #e6e6e6;
    display: flex;
    flex-wrap: wrap;
    padding: 27px;

    .el-form-item {
        margin: 13px;
        width: calc(50% - 26px);
        max-width: 400px;
        box-sizing: border-box;
        position: relative;
    }

    .el-select {
        width: 100%;
    }

    &::v-deep {
        .el-form-item__label {
            font-size: 14px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 16px;
            margin-bottom: 8px;
        }

        .el-input__inner {
            border: 1px solid #e6e6e6;
            border-radius: 8px;
            padding-left: 12px;
            padding-right: 12px;
            &::placeholder {
                font-size: 14px;
                color: #9e9e9e;
            }

            &:hover {
                border-color: #c7c7c7;
                box-shadow: initial;
            }

            &:focus {
                border-color: #f6b2cd;
                box-shadow: 0 0 1px 1px #f6b2cd;
            }
        }

        .el-form-item__error {
            position: absolute;
            left: 0;
            top: 100%;
            margin-top: 4px;
            font-size: 12px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #940306;
            line-height: 14px;
        }
        .el-form-item__content {
            line-height: 32px;
            vertical-align: top;

            .account-change-email {
                position: absolute;
                margin-left: 12px;
                left: 100%;
                bottom: 0;
                width: 82px;
                height: 32px;
                background: #f7f7f7;
                border-radius: 4px;
                border: 1px solid #d9d9d9;
            }
        }
    }

    .account-submit {
        position: fixed;
        left: 228px;
        right: 0;
        bottom: 0;
        padding: 0 32px;
        height: 72px;
        background: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        pointer-events: none;
        transition: all 0.2s;
        z-index: 11;
        border-top: 1px solid #e6e6e6;

        button {
            width: 140px;
            height: 40px;
        }

        &.active {
            opacity: 1;
            pointer-events: all;
        }
    }
}

.account-email {
    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #e6e6e6;
    padding: 0 24px;
    li {
        padding: 26px 0;
        display: flex;
        align-items: center;
        position: relative;

        & + li {
            border-top: 1px solid #ebebeb;
        }

        img {
            width: 32px;
            height: 32px;
            margin-right: 20px;
        }
        p {
            display: flex;
            flex-direction: column;
            flex: 1;

            strong {
                font-size: 16px;
                display: flex;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #000000;
                line-height: 18px;

                &::after {
                    content: 'Unsubscribed';
                    margin-left: 8px;
                    background: rgba(#555, 0.06);
                    border-radius: 6px;
                    padding: 0 4px;
                    font-size: 12px;
                    font-family: Roboto-Regular, Roboto;
                    font-weight: 400;
                    color: #555;
                    line-height: 18px;
                }
            }

            span {
                margin-top: 6px;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #555;
                line-height: 16px;
            }
        }

        em {
            width: 38px;
            height: 20px;
            background: #d6d6d6;
            border-radius: 12px;
            border: 1px solid #d6d6d6;
            box-sizing: border-box;
            position: relative;
            cursor: pointer;
            transition: all 0.2s;

            &:hover {
                background: #dbdbdb;
            }

            &::before {
                content: '';
                position: absolute;
                left: 1px;
                top: 1px;
                width: 16px;
                height: 16px;
                background: #fcfcfc;
                box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);
                border-radius: 11px;
                transition: all 0.2s;
            }
        }

        &.active {
            p strong::after {
                content: 'Subscribed';
                background: rgba(#007a4c, 0.06);
                color: #007a4c;
            }
            em {
                background: #ea4c89;
                border: 1px solid #d5417a;
                &:hover {
                    background: #c94175;
                }
                &::before {
                    left: 20px;
                }
            }
        }
    }
}
.account-loginInfo {
    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #e6e6e6;
    position: relative;
    padding: 22px 32px;
    display: flex;
    flex-direction: column;

    & > p {
        margin: 12px 0;
        line-height: 18px;
        display: flex;
        align-items: center;
        img {
            width: 18px;
            height: 18px;
        }
        span {
            width: 160px;
            font-size: 16px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #555555;
            line-height: 18px;
            margin-left: 24px;
        }
        strong {
            font-size: 16px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 18px;
        }
        em {
            color: #000;
        }
    }

    button {
        position: absolute;
        width: 88px;
        height: 36px;
        right: 34px;
        top: 50%;
        margin-top: -18px;
    }
}

.account-notify {
    display: flex;
    align-items: center;
    border-top: 1px solid #f2f2f2;
    border-bottom: 1px solid #f2f2f2;

    & + .account-notify {
        border-top: none;
    }

    strong {
        display: block;
        height: 18px;
        font-size: 16px;

        font-weight: normal;
        color: #000000;
        line-height: 18px;
        font-weight: normal;
    }
    span {
        margin-top: 16px;
        display: block;
        font-size: 14px;

        color: #666666;
        line-height: 16px;
        font-weight: normal;
    }

    p {
        flex: 1;
        padding: 28px 0;
        font-size: 14px;

        color: #666666;
        line-height: 16px;
        margin-right: 50px;
    }
}
.account-delete {
    padding: 34px 0 160px;
    p {
        font-size: 14px;

        color: #838383;
        line-height: 16px;
    }
    button {
        margin-top: 18px;
        width: 200px;
        height: 38px;
        background: #ffffff;
        border: 1px solid #d9d9d9;
        font-size: 14px;

        font-weight: normal;
        color: #666666;
    }
}
</style>
